package com.neuedu.hisboot.controller;

import com.neuedu.hisboot.dto.LoginDTO;
import com.neuedu.hisboot.dto.Result;
import com.neuedu.hisboot.entity.User;
import com.neuedu.hisboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jaun
 * @since 2025-07-04
 */
//@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public Result<User> login(@RequestBody LoginDTO loginDTO) {
        User user = userService.login(loginDTO.getUsername(), loginDTO.getPassword());

        if (user == null) {
            return Result.error(401, "用户名或密码错误");
        }

        // 实际项目中应返回 token 而不是完整用户信息
        return Result.success(user);
    }

    @GetMapping("/get/{deptId}")
    public Result<List<User>> getUsersByDeptId(@PathVariable("deptId") Integer deptId) {
        List<User> userList = userService.getUsersByDeptId(deptId);
        // 清除敏感信息
        userList.forEach(user -> user.setPassword(null));
        return Result.success(userList);
    }

    /**
     * 获取所有用户
     */
    @GetMapping("/list")
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.list();
        // 清除敏感信息
        users.forEach(user -> user.setPassword(null));
        return Result.success(users);
    }

    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.error(500, "未找到对应的用户");
        }
        // 清除敏感信息
        user.setPassword(null);
        return Result.success(user);
    }

    /**
     * 创建新用户
     */
    @PostMapping("/create")
    public Result<User> createUser(@RequestBody User user) {
        try {

            boolean success = userService.save(user);
            if (success) {
                user.setPassword(null); // 清除敏感信息
                return Result.success(user);
            } else {
                return Result.error(500, "创建用户失败");
            }
        } catch (Exception e) {
            return Result.error(500, "创建用户时发生错误: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    public Result<User> updateUser(@RequestBody User user) {
        try {
            boolean success = userService.updateById(user);
            if (success) {
                user.setPassword(null); // 清除敏感信息
                return Result.success(user);
            } else {
                return Result.error(500, "更新用户失败");
            }
        } catch (Exception e) {
            return Result.error(500, "更新用户时发生错误: " + e.getMessage());
        }
    }

    /**
     * 删除用户（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteUser(@PathVariable("id") Integer id) {
        try {
            User user = userService.getById(id);
            if (user == null) {
                return Result.error(500, "未找到对应的用户");
            }
            
            // 逻辑删除
            boolean success = userService.updateById(user);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error(500, "删除用户失败");
            }
        } catch (Exception e) {
            return Result.error(500, "删除用户时发生错误: " + e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/changePassword")
    public Result<String> changePassword(@RequestParam("userId") Integer userId, 
                                        @RequestParam("oldPassword") String oldPassword,
                                        @RequestParam("newPassword") String newPassword) {
        try {
            boolean success = userService.changePassword(userId, oldPassword, newPassword);
            if (success) {
                return Result.success("密码修改成功");
            } else {
                return Result.error(500, "密码修改失败，请检查原密码是否正确");
            }
        } catch (Exception e) {
            return Result.error(500, "修改密码时发生错误: " + e.getMessage());
        }
    }

    /**
     * 根据用户类型获取用户列表
     */
    @GetMapping("/type/{userType}")
    public Result<List<User>> getUsersByType(@PathVariable("userType") Integer userType) {
        List<User> users = userService.getByUserType(userType);
        // 清除敏感信息
        users.forEach(user -> user.setPassword(null));
        return Result.success(users);
    }

    /**
     * 根据科室获取用户列表
     */
    @GetMapping("/dept/{deptId}")
    public Result<List<User>> getUsersByDept(@PathVariable("deptId") Integer deptId) {
        List<User> users = userService.getByDeptId(deptId);
        // 清除敏感信息
        users.forEach(user -> user.setPassword(null));
        return Result.success(users);
    }

}
